package com.nowcoder.community.d_controller;


import com.nowcoder.community.a_entity.Comment;
import com.nowcoder.community.a_entity.DiscussPost;
import com.nowcoder.community.a_entity.Event;
import com.nowcoder.community.c1_kafka.EventProducer;
import com.nowcoder.community.c_service.CommentService;
import com.nowcoder.community.c_service.DiscussPostService;
import com.nowcoder.community.z_util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.nowcoder.community.z_util.CommunityConstant;

@Component
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {
    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private EventProducer eventProducer;

    //提交帖子内部的1、2级评论不用ajax【注意：1,2级都是comment表，用type在service里判就行，显示12级是之前写好的前端自动处理type==12】
    @RequestMapping(path = "/add/{postId}",method = RequestMethod.POST)
    public String add1jiCommentInOnePost(Model model,
                                      @PathVariable("postId") int postId,
                                      Comment comment//form自动用name装
                                      )
    {
        //form-name剩了一些要人工加入（service中）+敏感


        //这里面核心 1敏感评论 2更新comm表 3更新post表的count！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
        commentService.addComment(comment);

        //+kafka系统通知
        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId",postId);


        //根据type识别出id是应该在哪个表用（e_type,e_id都是add时写好的，关键是用的时候根据tpye识别id在哪用）
        //不用表中用这个e_id主键————>（查出row*POJO）
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost target = discussPostService.findPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        } else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        //放入生产者之后就不管了（消费者负责cpu空闲时写入sql）
        eventProducer.fireEvent(event);




        return "redirect:/discuss/detail/"+postId;//直接看网站url，不用从头分析进入帖子是啥url
        //?offset=0&limit=5&current=1这个是点分页按钮才出现，第一次index进入帖子不用
    }

}
